package com.chain.BrotherExchange.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.LegalTenderDealList;
import com.chain.BrotherExchange.data.model.UserPayment;
import com.chain.BrotherExchange.event.EditTransactionOrderEvent;
import com.chain.BrotherExchange.ui.core.AbsNetworkStateActivity;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.viewmodel.PaymentViewModel;
import com.chain.BrotherExchange.viewmodel.PublishTransactionOrderViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * 编辑发布过的交易订单
 */
public class EditTransactionOrderActivity extends AbsNetworkStateActivity {

    @Bind(R.id.balance_text_view) TextView balanceTextView;
    @Bind(R.id.token_symbol_text) TextView tokenSymbolText;
    @Bind(R.id.unit_price_text) TextView unitPriceText;
    @Bind(R.id.number_text) EditText numberText;
    @Bind(R.id.token_symbol_two_text) TextView tokenSymbolTwoText;
    @Bind(R.id.lowest_price_edit) EditText lowestPriceEdit;
    @Bind(R.id.highest_price_edit) EditText highestPriceEdit;
    @Bind(R.id.bank_card_payment_check) CheckBox bankCardPaymentCheck;
    @Bind(R.id.bank_card_payment_layout) FrameLayout bankCardPaymentLayout;
    @Bind(R.id.ali_pay_check) CheckBox aliPayCheck;
    @Bind(R.id.ali_pay_layout) FrameLayout aliPayLayout;
    @Bind(R.id.we_chat_pay_check) CheckBox weChatPayCheck;
    @Bind(R.id.we_chat_pay_layout) FrameLayout weChatPayLayout;
    @Bind(R.id.pay_pal_check) CheckBox payPalCheck;
    @Bind(R.id.pay_pal_layout) FrameLayout payPalLayout;
    @Bind(R.id.premium_text) EditText premiumText;
    @Bind(R.id.free_statement_view) TextView freeStatementView;
    @Bind(R.id.max_price_edit) EditText maxPriceEdit;
    @Bind(R.id.remark_edit) EditText remarkEdit;
    @Bind(R.id.authentication_switch) SwitchCompat authenticationSwitch;
    @Bind(R.id.more_content_layout) LinearLayout moreContentLayout;
    @Bind(R.id.more_content_hint_text) TextView moreContentHintText;
    @Bind(R.id.more_content_hint_image) AppCompatImageView moreContentHintImage;
    @Bind(R.id.look_more_content_layout) LinearLayout lookMoreContentLayout;
    @Bind(R.id.apply_button) Button applyButton;

    private PublishTransactionOrderViewModel mViewModel;
    private List<String> mPaymentTypeList = new ArrayList<>();
    private LegalTenderDealList.DataBean.ListBean mOrderDetails;

    public static void launch(Context context, Serializable serializable) {
        context.startActivity(new Intent(context, EditTransactionOrderActivity.class)
                .putExtra(C.EXTRA_TRANSACTION_ORDER_DETAILS, serializable)
        );
    }

    @Override
    public int getTitleLayoutRes() {
        return R.layout.layout_default_title_bar;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_edit_transaction_order;
    }

    @Override
    protected void initActions() {
        ActivityBarHelper.init(this, R.string.title_edit_transaction_order);

        // 交易订单详情
        mOrderDetails = (LegalTenderDealList.DataBean.ListBean)
                getIntent().getSerializableExtra(C.EXTRA_TRANSACTION_ORDER_DETAILS);

        mViewModel = ViewModelProviders.of(this).get(PublishTransactionOrderViewModel.class);

        // 支付方式
        initMyPayments();

        // 加载订单视图
        loadOrderView();

        // 账户余额
        loadSingleCoinBalance();

        // 发布
        applyButton.setOnClickListener(v -> publishOrder());

        // 切换可见或不可见
        lookMoreContentLayout.setOnClickListener(v -> switchMoreContentView());

        // 免责声明
        freeStatementView.setOnClickListener(v -> WebViewActivity.freeStatement(this));
    }

    private void loadOrderView() {
        tokenSymbolText.setText(mOrderDetails.getToken_name());
        tokenSymbolTwoText.setText(mOrderDetails.getToken_name());
        numberText.setText(mOrderDetails.getNumText());
        lowestPriceEdit.setText(mOrderDetails.getMinLimitText());
        highestPriceEdit.setText(mOrderDetails.getMaxLimitText());
        premiumText.setText(String.valueOf(mOrderDetails.getPremium()));

        // 支付方式回显
        String pays = mOrderDetails.getPays();
        if (!TextUtils.isEmpty(pays)) {
            String[] paymentArr = pays.split(",");
            for (int i = 0; i < paymentArr.length; i++) {
                String payment = paymentArr[i];
                switch (payment) {
                    case "1":
                        bankCardPaymentCheck.setChecked(true);
                        break;
                    case "2":
                        aliPayCheck.setChecked(true);
                        break;
                    case "3":
                        weChatPayCheck.setChecked(true);
                        break;
                    case "4":
                        payPalCheck.setChecked(true);
                        break;
                }
            }
        }
    }

    private void loadSingleCoinBalance() {
        int tokenId = mOrderDetails.getToken_id();
        mViewModel.singleCoinBalance(tokenId).observe(this, balance ->
                balanceTextView.setText(getString(R.string.legal_currency_account_balance)
                        + balance.getBalance() + " ")
        );

        mViewModel.unitPrice(tokenId).observe(this, price -> {
            unitPriceText.setText(price);
        });
    }

    private void initMyPayments() {
        bankCardPaymentCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mPaymentTypeList.add(String.valueOf(1));
            } else {
                mPaymentTypeList.remove(String.valueOf(1));
            }
        });
        aliPayCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mPaymentTypeList.add(String.valueOf(2));
            } else {
                mPaymentTypeList.remove(String.valueOf(2));
            }
        });
        weChatPayCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mPaymentTypeList.add(String.valueOf(3));
            } else {
                mPaymentTypeList.remove(String.valueOf(3));
            }
        });
        payPalCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mPaymentTypeList.add(String.valueOf(4));
            } else {
                mPaymentTypeList.remove(String.valueOf(4));
            }
        });

        PaymentViewModel viewModel = ViewModelProviders.of(this).get(PaymentViewModel.class);
        viewModel.userPayment().observe(this, resource ->
                Resource.load(this, resource, this, result ->
                        initPaymentSelector(result.getSetpays()))
        );
    }

    private void publishOrder() {
        int id = mOrderDetails.getId();
        String number = numberText.getText().toString();
        String price = unitPriceText.getText().toString();
        String lowestPrice = lowestPriceEdit.getText().toString();
        String heightPrice = highestPriceEdit.getText().toString();
        boolean isVerify = authenticationSwitch.isChecked();
        String premium = premiumText.getText().toString();
        String acceptPrice = maxPriceEdit.getText().toString();
        String remarkText = remarkEdit.getText().toString();

        mViewModel.editPublishOrder(id, price, number, premium, acceptPrice, lowestPrice,
                heightPrice, isVerify, mPaymentTypeList, remarkText)
                .observe(this, resource -> {
                    if (resource.state == Resource.Status.LOADING) {
                        Androids.showProgressMessage(this, getString(R.string.publish_trade_ordering));
                    } else {
                        Androids.dismissProgressMessage();
                        Androids.makeText(resource.message);
                        if (resource.state == Resource.Status.SUCCESS) {
                            EventBus.getDefault().post(new EditTransactionOrderEvent());
                            finish();
                        }
                    }
                });
    }

    private void initPaymentSelector(UserPayment.DataBean.SetpaysBean payment) {
        // 1
        bankCardPaymentLayout.setVisibility(payment.getBank_pay() == 0 ? View.GONE : View.VISIBLE);

        // 3
        aliPayLayout.setVisibility(payment.getAli_pay() == 0 ? View.GONE : View.VISIBLE);

        // 2
        weChatPayLayout.setVisibility(payment.getWechat_pay() == 0 ? View.GONE : View.VISIBLE);

        // 4
        payPalLayout.setVisibility(payment.getPaypal_pay() == 0 ? View.GONE : View.VISIBLE);
    }

    private void switchMoreContentView() {
        if (moreContentLayout.getVisibility() != View.VISIBLE) {
            moreContentLayout.setVisibility(View.VISIBLE);
            moreContentHintText.setText(R.string.collapse_more);
            moreContentHintImage.animate().rotation(270).start();
        } else {
            moreContentLayout.setVisibility(View.GONE);
            moreContentHintText.setText(R.string.see_more);
            moreContentHintImage.animate().rotation(90).start();
        }
    }

    @Override
    public void onAnewRequest() {
        initMyPayments();
    }
}
